const boom = require("boom");

const JWTToken = require("../models/token");
const { verifyToken } = require("./../utils/authorization");

module.exports.checkAuth = async (req, reply) => {
  try {
    const { headers } = req;
    const existingToken = await JWTToken.findOne({ token: headers.token });
    if (!existingToken) {
      throw boom.unauthorized("Token 无效");
    }

    const data = await verifyToken(headers.token);
    req.user = data; // 将解码后的用户数据附加到请求对象上
  } catch (err) {
    throw boom.boomify(err);
  }
};
